﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Sasa.QualityTools.CodeAnalysis.Common;

namespace Sasa.QualityTools.CodeAnalysis.Core.Models
{
    public class CodeAnalysisResultValueFileNameFilter : ICodeAnalysisResultValueFilter
    {
        public ICollection<string> Patterns { get; private set; }


        public CodeAnalysisResultValueFileNameFilter()
        {
            Patterns = new List<string>();
        }

        public CodeAnalysisResultValueFileNameFilter(IEnumerable<string> patterns)
            :this()
        {
            foreach (var pattern in patterns)
            {
                Patterns.Add(pattern);
            }
        }


        public bool IsAvailable(CodeAnalysisResultValueBase value)
        {
            if (value == null)
            {
                return false;
            }

            string fileName = null;
            try
            {
                fileName = Path.GetFileName(value.Path);
            }
            catch (ArgumentException ex)
            {
                Logger.Error(ex, "Ignored the specified code analysis result value.");
                return true;
            }

            foreach (var pattern in Patterns)
            {
                try
                {
                    if (Regex.IsMatch(fileName, pattern))
                    {
                        return false;
                    }
                }
                catch (ArgumentException ex)
                {
                    Logger.Error(ex, "Ignored the pattern '{0}'.", pattern);
                }
            }

            return true;
        }
    }
}
